using System;
using System.Collections.Generic;
using System.Text;
using MVP.Demo.Core;
using System.Web;

namespace MVP.Demo.Model
{
    public class PlayerRepository : IPlayerRepository
    {
        public List<PlayerDTO> GetPlayersForTeam(int teamID)
        {
            return GetPlayersFromCache();
        }

        public void SavePlayer(string firstName, string lastName, int teamID)
        {            
            PlayerDTO newPlayerDTO = new PlayerDTO();
            newPlayerDTO.FirstName = firstName;
            newPlayerDTO.LastName = lastName;
            newPlayerDTO.PlayerID = Guid.NewGuid().ToString();
            newPlayerDTO.TeamID = teamID;
            SavePlayerToList(newPlayerDTO);
        }

        public void DeletePlayer(string playerID)
        {
            List<PlayerDTO> players = GetPlayersFromCache();
            foreach (PlayerDTO dto in players)
            {
                if (dto.PlayerID == playerID)
                {
                    RemovePlayerFromList(dto);
                    break;
                }
            }
        }

        private List<PlayerDTO> GeneratePlayerList()
        {
            PlayerDTO dto1 = new PlayerDTO();
            dto1.PlayerID = Guid.NewGuid().ToString();
            dto1.FirstName = "Donovan";
            dto1.LastName = "McNabb";
            dto1.TeamID = 1;

            PlayerDTO dto2 = new PlayerDTO();
            dto2.PlayerID = Guid.NewGuid().ToString();
            dto2.FirstName = "Jevon";
            dto2.LastName = "Kearse";
            dto2.TeamID = 1;

            List<PlayerDTO> players = new List<PlayerDTO>();
            players.Add(dto1);
            players.Add(dto2);

            return players;
        }

        private List<PlayerDTO> GetPlayersFromCache()
        {
            List<PlayerDTO> players = HttpRuntime.Cache["PlayerList"] as List<PlayerDTO>;
            if (players == null)
            {
                HttpRuntime.Cache["PlayerList"] = GeneratePlayerList();
            }
            return HttpRuntime.Cache["PlayerList"] as List<PlayerDTO>;
        }

        private void SavePlayerToList(PlayerDTO newPlayerDTO)
        {
            List<PlayerDTO> players = GetPlayersFromCache();
            players.Add(newPlayerDTO);
            HttpRuntime.Cache["PlayerList"] = players;
        }

        private void RemovePlayerFromList(PlayerDTO dto) 
        {
            List<PlayerDTO> players = GetPlayersFromCache();
            players.Remove(dto);
            HttpRuntime.Cache["PlayerList"] = players;
        }
    }
}